package com.vf.admin.client.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.vf.admin.client.common.ClientBaseController;
import com.vf.admin.client.common.ClientConstants;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.client.dao.AppOrderDao;
import com.vf.admin.client.service.*;
import com.vf.admin.client.service.pay.AppPaySetupLoadBalancer;
import com.vf.admin.client.service.pay.WxPayService;
import com.vf.admin.common.Constants;
import com.vf.admin.common.entity.Result;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.fiwork.util.IOSVerify;
import com.vf.admin.miaodong.entity.*;
import com.vf.admin.utils.GenerateOrderNum;
import com.vf.admin.utils.HttpClient;
import com.vf.admin.utils.pay.ApiAliPay.AlipayConfig;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.vf.admin.utils.RandomUtil.getOrderIdByUUId;

@RestController
@RequestMapping("/app/vip")
public class AppVipPackageController extends ClientBaseController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    VipPackageService vipPackageService;
    @Autowired
    AppUserService appUserService;
    @Autowired
    VipOrderService vipOrderService;
    @Autowired
    WxPayService wxPayService;
    @Autowired
    AppSetupService setupService;
    @Autowired
    private AppSetupService appSetupService;//ttyb
    @Autowired
    AppCzMoneyService appCzMoneyService;//ttyb
    @Autowired
    private AppOrderDao appOrderDao;//ttyb
    @Autowired
    private AppPaySetupLoadBalancer appPaySetupLoadBalancer;

    @RequestMapping(value = "/list")
    public Result list() {
        Map<String, Object> data = new HashMap<>();
        Map<String, Object> userMap = new HashMap<>();

        List<VipPackage> vipPackageList = vipPackageService.list();

        AppUser appUser = appUserService.get(getUserId());
        if (appUser != null) {
            userMap.put("pic", StringUtils.isBlank(appUser.getPic()) ? "" : appUser.getPic());
            userMap.put("nick", StringUtils.isBlank(appUser.getNick()) ? "" : appUser.getNick());
            Map<String, Object> vipMap = appUserService.isVipMap(getUserId());
            userMap.putAll(vipMap);

            data.put("list", vipPackageList);
            data.put("user", userMap);
        }
        return this.sucessJSON(data);
    }

    /**
     * 开通会员
     *
     * @param id payType 1微信 2支付宝 3内购
     * @return
     */
    @RequestMapping(value = "/openVip")
    public Result openVip(Integer id, Integer payType) {
        AppSetup setup = setupService.get();
        if (setup.getOpenBuyVip() == 0) {
            return this.errorJSON(setup.getBuyVipTip());
        }
        String orderNo = GenerateOrderNum.getInstance().generateOrderNo();
        VipOrder order = new VipOrder();
        order.setUserId(getUserId());
        order.setOrderNo(orderNo);
        order.setVipPackageId(id);
        order.setStatus(0);
        if (payType == 1) {
            order.setPayType("weixin");
        } else if (payType == 2) {
            order.setPayType("alipay");
        } else if (payType == 3) {
            order.setPayType("IOS");
        }
        order.setCreateTime(new Date());
        vipOrderService.save(order);
        VipPackage vipPackage = vipPackageService.info(id);
        Map<String, String> map = new HashMap<>();
        if (payType == 1) {
            Map<String, String> params = new HashMap<>();
            params.put("body", "开通贵族");
            params.put("orderNo", orderNo);
            params.put("money", vipPackage.getPrice().stripTrailingZeros().toPlainString());
            params.put("notifyUrl", wxPayService.notify_vip_url);
            params.put("payFrom", "APP");
            String result = HttpClient.doPost("http://127.0.0.1:8092/wxSign", params);
            Map<String, Object> signMap = JSON.parseObject(result, Map.class);
            return this.sucessJSON(signMap);
        } else if (payType == 2) {
            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
            model.setBody("开通贵族");
            model.setSubject("开通贵族");
            model.setOutTradeNo(orderNo);
            model.setTotalAmount(vipPackage.getPrice().stripTrailingZeros().toPlainString());
            model.setProductCode("QUICK_MSECURITY_PAY");
            AppPaySetup appPaySetup = appPaySetupLoadBalancer.getNextAlipayAppPaySetup();
            //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
            AlipayTradeAppPayRequest aliRequest = new AlipayTradeAppPayRequest();
            aliRequest.setBizModel(model);
            aliRequest.setNotifyUrl(appPaySetup.getNotifyVipUrl());
            //返回支付宝订单信息(预处理)
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.GATEWAYURL,
                    appPaySetup.getAppId(), appPaySetup.getAppPrivateKey(),
                    AlipayConfig.FORMAT, AlipayConfig.CHARSET, appPaySetup.getAlipayPublicKey(),
                    AlipayConfig.SIGN_TYPE);
            String orderString = "";
            try {
                AlipayTradeAppPayResponse alipayTradeAppPayResponse = alipayClient.sdkExecute(aliRequest);
                orderString = alipayTradeAppPayResponse.getBody();
            } catch (Exception e) {
                e.printStackTrace();
            }
            map.put("orderString", orderString);
        } else if (payType == 3) {
            map.put("orderNo", orderNo);
        }
        return this.sucessJSON(map);
    }

    /**
     * 开通会员H5
     *
     * @param id payType 1微信 2支付宝
     * @return
     */
    @RequestMapping(value = "/openVipByWeb")
    public Result openVipByWeb(Integer id, Integer payType) {
        AppSetup setup = setupService.get();
        if (setup.getOpenBuyVip() == 0) {
            return this.errorJSON(setup.getBuyVipTip());
        }
        String orderNo = GenerateOrderNum.getInstance().generateOrderNo();
        VipOrder order = new VipOrder();
        //
        order.setUserId(getUserId());
        order.setOrderNo(orderNo);
        order.setVipPackageId(id);
        order.setStatus(0);
        if (payType == 1) {
            order.setPayType("weixin");
        } else if (payType == 2) {
            order.setPayType("alipay");
        }
        order.setCreateTime(new Date());
        vipOrderService.save(order);

        VipPackage vipPackage = vipPackageService.info(id);
        String orderString = "";
        if (payType == 1) {
            Map<String, String> params = new HashMap<>();
            params.put("body", "开通贵族");
            params.put("orderNo", orderNo);
            params.put("money", vipPackage.getPrice().stripTrailingZeros().toPlainString());
            params.put("notifyUrl", wxPayService.notify_vip_url);
            params.put("payFrom", "APP");
            String result = HttpClient.doPost("http://127.0.0.1:8092/wxSign", params);
            Map<String, Object> signMap = JSON.parseObject(result, Map.class);
            return this.sucessJSON(signMap);
        } else if (payType == 2) {
            AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
            AppPaySetup appPaySetup = appPaySetupLoadBalancer.getNextAlipayAppPaySetup();
            model.setBody("开通贵族");
            model.setSubject("开通贵族");
            model.setOutTradeNo(orderNo);
            model.setTotalAmount(vipPackage.getPrice().stripTrailingZeros().toPlainString());
            model.setProductCode("QUICK_WAP_PAY");
            model.setQuitUrl(appPaySetup.getVipQuitUrl());
            //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
            AlipayTradeWapPayRequest aliRequest = new AlipayTradeWapPayRequest();
            aliRequest.setBizModel(model);
            aliRequest.setNotifyUrl(appPaySetup.getNotifyVipUrl());
            aliRequest.setReturnUrl(appPaySetup.getVipReturnUrl());
            //返回支付宝订单信息(预处理)
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.GATEWAYURL,
                    appPaySetup.getAppId(), appPaySetup.getAppPrivateKey(),
                    AlipayConfig.FORMAT, AlipayConfig.CHARSET, appPaySetup.getAlipayPublicKey(),
                    AlipayConfig.SIGN_TYPE);

            try {
                orderString = alipayClient.pageExecute(aliRequest).getBody();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return this.sucessJSON(orderString);
    }

    /**
     * 充值H5
     *
     * @param id payType 1微信 2支付宝
     * @return
     */
    @RequestMapping(value = "/openZsByWeb")
    public Result openZsByWeb(HttpServletRequest request, Double money, Integer id, Integer payType) {
        try {
            AppSetup setup = appSetupService.get();
            if (setup.getOpenRecharge() == 0) {
                return this.errorJSON(setup.getRechargeTip());
            }
            Map<String, Object> data = new HashMap<>();
            if (money == null || money <= 0) {
                return this.errorJSON("请你输入充值金额!");
            }
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            AppUser user = appUserService.get(userId);
            AppCzMoney appCzMoney = appCzMoneyService.get(id);
            BigDecimal getDiamond = appCzMoney.getDiamonds().add(appCzMoney.getGive());
            //添加订单记录
            String orderNum = getOrderIdByUUId();
            AppOrder appOrder = new AppOrder();
            appOrder.setCreatetime(new Date());
            appOrder.setOrdernum(orderNum);
            appOrder.setCzMoneyId(id);
            appOrder.setMoney(new BigDecimal(appCzMoney.getMoney()));
            appOrder.setStatus(Constants.dingdan_status_dfk);
            appOrder.setType(payType);//type
            appOrder.setUserid(user.getId());
            appOrder.setPic(user.getPic());
            appOrder.setNick(user.getNick());
            appOrder.setPhone(user.getLoginname());
            appOrder.setNum(getDiamond);
            appOrderDao.save(appOrder);
            String orderString = "";
            if (payType == 1) {
                Map<String, String> params = new HashMap<>();
                params.put("body", "钻石充值");
                params.put("orderNo", orderNum);
                params.put("money", money.toString());
                params.put("notifyUrl", wxPayService.notify_vip_url);
                params.put("payFrom", "APP");
                String result = HttpClient.doPost("http://127.0.0.1:8092/wxSign", params);
                Map<String, Object> signMap = JSON.parseObject(result, Map.class);
                return this.sucessJSON(signMap);
            } else if (payType == 2) {
                AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
                AppPaySetup appPaySetup = appPaySetupLoadBalancer.getNextAlipayAppPaySetup();
                model.setBody("钻石充值");
                model.setSubject("钻石充值");
                model.setOutTradeNo(orderNum);
                model.setTotalAmount(money.toString());
                model.setProductCode("QUICK_WAP_PAY");
                model.setQuitUrl(appPaySetup.getVipQuitUrl());
                //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
                AlipayTradeWapPayRequest aliRequest = new AlipayTradeWapPayRequest();
                aliRequest.setBizModel(model);
                aliRequest.setNotifyUrl(appPaySetup.getNotifyVipUrl());
                aliRequest.setReturnUrl(appPaySetup.getVipReturnUrl());
                //返回支付宝订单信息(预处理)
                AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.GATEWAYURL,
                        appPaySetup.getAppId(), appPaySetup.getAppPrivateKey(),
                        AlipayConfig.FORMAT, AlipayConfig.CHARSET, appPaySetup.getAlipayPublicKey(),
                        AlipayConfig.SIGN_TYPE);

                try {
                    orderString = alipayClient.pageExecute(aliRequest).getBody();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return this.sucessJSON(orderString);
        } catch (Exception e) {
            logger.error("支付宝充值异常:", e);
            return this.errorJSON("服务器繁忙，请您稍后重试!");
        }

    }

    /**
     * ios内购回调
     *
     * @param receipt
     * @return
     */
    @RequestMapping("/iosPaySuccess")
    public Result iosPaySuccess(@RequestParam("orderNo") String orderNo, @RequestParam("receipt") String receipt) {
        try {
            receipt = URLDecoder.decode(receipt, "utf-8");
            logger.info("----------------------receipt Str:" + receipt);
            Map<String, Object> result = IOSVerify.buyAppVerify(receipt);
            if (result.get("success").toString().equals("true")) {
                String externalOrderNo = (String) result.get("transaction_id");
                vipOrderService.successCall(orderNo);
            } else {
                return errorJSON("IOS内购验证失败");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return result;

    }
}
